package lrz.shiftplanner.calendar;

import java.util.*;

public class Month {
	
	
	class DayElement {
		Day day;
		DayElement prev;
		DayElement next;
	}
	
	private LinkedList<DayElement> days;
	private Meeting meeting;
	private HashMap<Day, DayElement> map;
	
	private int shiftCount;
	private int shiftRemaining;

	public Month(int year, int month) {
		days = new LinkedList<Month.DayElement>();
		//meeting = new Meeting();
		shiftCount = 0;
		map = new HashMap<Day, Month.DayElement>();

		GregorianCalendar g = new GregorianCalendar();
		g.clear();
		g.set(year, month, 1);
		DayElement curr = new DayElement();
		int k=0;
		// add each day of the month to the linked list
		while (g.get(Calendar.MONTH) == month) {
			DayElement de = new DayElement();
			if (k!=0)
				curr.next = de;
			de.prev = curr;
			curr = de;
			curr.day = new Day (this, g.getTime(), HolidayCalculator.getDayType(g.getTime()));
			days.add(curr);
			map.put(curr.day, curr);
			
			// progress one day
			g.add(Calendar.DATE, 1);
			k++;
		}
		calcShiftCounts();
	}
	
	public void calcShiftCounts() {
		shiftCount = 0;
		shiftRemaining = 0;
		for (DayElement de : days) {
			shiftCount += de.day.getTotalShiftNumber();
			shiftRemaining += de.day.getRemainingShiftNumber();
		}
	}
	
	public Day getPreviousDay(Day day) {
		DayElement de = map.get(day).prev;
		if (de!=null)
			return de.day;
		else
			return null;
	}
	
	public Day getNextDay(Day day) {
		DayElement de = map.get(day).next;
		if (de!=null)
			return de.day;
		else
			return null;
	}
	
	public int getShiftCount() {
		return shiftCount;
	}
	
	public int getRemainingShiftCount() {
		return shiftRemaining;
	}
	
	public void setRemainingShiftCount(int shiftCount) {
		shiftRemaining = shiftCount;
	}


	public Meeting getMeeting() {
		return meeting;
	}
	
	public boolean isMeetingDay(Day d) {
		return (getMeeting()!=null && getMeeting().day.equals(d));
	}
	
	
	public int getDayIndex(Day day) {
		int k=0;
		for (DayElement d : days) {
			if (day.getDate().equals(d.day.getDate()))
				return k;
			k++;
		}
		return -1;
	}
	
	public int getMeetingDayIndex() {
		if (meeting==null)
			return -1;
		else
			return getDayIndex(meeting.day);
	}
	
	public Day getDay(int index) {
		return days.get(index).day;
	}
	
	public int getDayCount() {
		return days.size();
	}

	public void setMeeting(Meeting meeting) {
		this.meeting = meeting;
		
	}
	
	
}
